from Config.myConstant import *
from Config.myConfig import *
from DataPrepare.tickFactorsLongTerm.factorBase import factorBase
from DataAccess.TickDataProcess import TickDataProcess
import pandas as pd
import numpy as np
import math


########################################################################
class buySellForce(factorBase):
    """描述盘口状态的因子"""

    # ----------------------------------------------------------------------
    def __init__(self):
        # super(buySellVolumeRatio,self).__init__()
        super().__init__()
        self.factor = 'buySellForce'
        pass

    # ----------------------------------------------------------------------
    def getFactorFromLocalFile(self, code, date):
        mydata = super().getFromLocalFile(code, date, 'buySellForce')
        return mydata
        pass

    # ----------------------------------------------------------------------
    def updateFactor(self, code, date, data=pd.DataFrame()):
        exists = super().checkLocalFile(code, date, self.factor)
        if exists == True:
            logger.info(f'No need to compute! {self.factor} of {code} in {date} exists!')
            pass
        if data.shape[0] == 0:
            # data=TickDataProcess().getDataByDateFromLocalFile(code,date)
            data = TickDataProcess().getTickShotDataFromInfluxdbServer(code, date)
        result = self.computerFactor(code, date, data)
        super().updateFactor(code, date, self.factor, result)

    # ----------------------------------------------------------------------
    def __logBetweenTwoColumns(self, data, col1, col2):
        return super().logBetweenTwoColumns(data, col1, col2)

    # ----------------------------------------------------------------------
    def __logBetweenTwoColumnsWithBound(self, data, col1, col2, bound):
        result = data[[col1, col2]].copy()
        result['change'] = self.__logBetweenTwoColumns(result, col1, col2)
        select = (result[col1] == 0) & (result[col2] > 0)
        result.loc[select, 'change'] = -bound
        select = (result[col1] > 0) & (result[col2] == 0)
        result.loc[select, 'change'] = bound
        return result['change']

    # ----------------------------------------------------------------------
    def __buySellPressure(self, data, volumeStart, volumeEnd):
        result = data.copy()
        result['buyVolume'] = 0
        result['sellVolume'] = 0
        for i in range(volumeStart, volumeEnd + 1):
            result['buyVolume'] = result['buyVolume'] + result['BV' + str(i)]
            result['sellVolume'] = result['sellVolume'] + result['SV' + str(i)]
            pass
        colname = 'buySellPressure'
        result[colname] = self.__logBetweenTwoColumns(result, 'buyVolume', 'sellVolume')
        return result[colname]
        pass

    # ----------------------------------------------------------------------
    def __averageVolumeWeighted(self, data, volumeStart, volumeEnd, decay):
        result = data.copy()
        result['buyAverageVolumeWeighted'] = 0
        result['sellAverageVolumeWeighted'] = 0
        for i in range(volumeStart, volumeEnd + 1):
            result['buyAverageVolumeWeighted'] = result['buyAverageVolumeWeighted'] + result['BV' + str(i)] * math.pow(
                decay, i - volumeStart)
            result['sellAverageVolumeWeighted'] = result['sellAverageVolumeWeighted'] + result[
                'SV' + str(i)] * math.pow(decay, i - volumeStart)
            pass
        result['buyAverageVolumeWeighted'] = result['buyAverageVolumeWeighted'] / (volumeEnd - volumeStart + 1)
        result['sellAverageVolumeWeighted'] = result['sellAverageVolumeWeighted'] / (volumeEnd - volumeStart + 1)
        return result[['buyAverageVolumeWeighted', 'sellAverageVolumeWeighted']]
        pass

    # ----------------------------------------------------------------------
    def __buySellVolumeWeightedPressure(self, data, volumeStart, volumeEnd, decay):
        result = data.copy()
        result[['buyAverageVolumeWeighted', 'sellAverageVolumeWeighted']] = self.__averageVolumeWeighted(data,
                                                                                                         volumeStart,
                                                                                                         volumeEnd,
                                                                                                         decay)
        result['buySellVolumeWeightedPressure'] = self.__logBetweenTwoColumns(result, 'buyAverageVolumeWeighted',
                                                                              'sellAverageVolumeWeighted')
        return result['buySellVolumeWeightedPressure']
        pass

    # ----------------------------------------------------------------------
    def __buySellAmountWeightedPressure(self, data, amountStart, amountEnd, decay):
        result = data.copy()
        result[['buyAverageAmountWeighted', 'sellAverageAmountWeighted']] = self.__averageAmountWeighted(data,
                                                                                                         amountStart,
                                                                                                         amountEnd,
                                                                                                         decay)
        select = (result['buyAverageAmountWeighted'] > 0) & (result['sellAverageAmountWeighted'] > 0)
        result['buySellAmountWeightedPressure'] = 0
        result.loc[select, 'buySellAmountWeightedPressure'] = (result['buyAverageAmountWeighted'] - result[
            'sellAverageAmountWeighted']) / (result['buyAverageAmountWeighted'] + result['sellAverageAmountWeighted'])
        return result['buySellAmountWeightedPressure']
        pass

    # ----------------------------------------------------------------------
    def __averageAmountWeighted(self, data, amountStart, amountEnd, decay):
        result = data.copy()
        result['buyAverageAmountWeighted'] = 0
        result['sellAverageAmountWeighted'] = 0
        for i in range(amountStart, amountEnd + 1):
            result['buyAverageAmountWeighted'] = result['buyAverageAmountWeighted'] + result['B' + str(i)] * result[
                'BV' + str(i)] * math.pow(decay, i - amountStart)
            result['sellAverageAmountWeighted'] = result['sellAverageAmountWeighted'] + result['S' + str(i)] * result[
                'SV' + str(i)] * math.pow(decay, i - amountStart)
            pass
        result['buyAverageAmountWeighted'] = result['buyAverageAmountWeighted'] / (amountEnd - amountStart + 1)
        result['sellAverageAmountWeighted'] = result['sellAverageAmountWeighted'] / (amountEnd - amountStart + 1)
        return result[['buyAverageAmountWeighted', 'sellAverageAmountWeighted']]
        pass

    # ----------------------------------------------------------------------
    def __buySellWeightedVolumeRatio(self, data, n):
        data['buyWeightedVolume' + str(n)] = 0
        data['sellWeightedVolume' + str(n)] = 0
        epsilon = 0.000001
        select0 = (data['B1'] > 0) & (data['S1'] > 0)
        for i in range(1, n + 1):
            select = (data['B' + str(i)] > 0) & select0
            data.loc[select, 'buyWeightedVolume' + str(n)] = data['buyWeightedVolume' + str(n)] + data['BV' + str(i)] * \
                                                             ((data['buySellSpread'] * data['midPrice'] + epsilon) / (
                                                                         data['midPrice'] - data[
                                                                     'B' + str(i)] + epsilon))[select]
            select = (data['S' + str(i)] > 0) & select0
            data.loc[select, 'sellWeightedVolume' + str(n)] = data['sellWeightedVolume' + str(n)] + data[
                'SV' + str(i)] * ((data['buySellSpread'] * data['midPrice'] + epsilon) / (
                        -data['midPrice'] + data['S' + str(i)] + epsilon))[select]
            pass
        data['buySellWeightedVolumeRatio' + str(n)] = data['buyWeightedVolume' + str(n)] / (
                    data['buyWeightedVolume' + str(n)] + data['sellWeightedVolume' + str(n)])
        select = data['B1'] == data['S1']
        data.loc[select, 'buySellWeightedVolumeRatio' + str(n)] = (data['BV1'] / (data['BV1'] + data['SV1']))[select]
        select = (data['B1'] == 0) | (data['S1'] == 0)
        data.loc[select, 'buySellWeightedVolumeRatio' + str(n)] = 0
        data['buyWeightedVolume' + str(n)] = np.log(data['buyWeightedVolume' + str(n)] + 1)
        data['sellWeightedVolume' + str(n)] = np.log(data['sellWeightedVolume' + str(n)] + 1)
        pass

    # ----------------------------------------------------------------------
    def __longTermVolumeIncreaeMean(self, data, code, date, span):
        result = data[['date', 'volumeIncrease']].copy()
        lastData = super().getLastTradedayTickData(code, date)
        if lastData.shape[0] > 0:
            lastData = lastData[lastData['tick'] < '145700000']
            last = lastData[['date', 'volumeIncrease']].copy()
            total = pd.concat([last, result])
        else:
            total = result
        total['volumeIncreaseMean'] = total['volumeIncrease'].rolling(span, min_periods=1).mean()
        select = total['date'] == date
        return total[select]['volumeIncreaseMean']
        pass

    # ----------------------------------------------------------------------
    def __buySellVolumeForce(self, data):
        mydata = data.copy()
        result = mydata.copy()
        select0 = mydata['S1'] != mydata['B1']
        result['buyForce'] = 0
        for i in range(1, 11):
            select = (mydata['S1'] > mydata['S' + str(i)].shift(1)) & select0
            result.loc[select, 'buyForce'] = \
            (result['buyForce'] + mydata['SV' + str(i)].shift(1) / result['buyVolume10'].shift(1))[select]
            select = (mydata['S1'] == mydata['S' + str(i)].shift(1)) & (
                        mydata['SV' + str(i)].shift(1) > mydata['SV1']) & select0
            result.loc[select, 'buyForce'] = \
            (result['buyForce'] + (mydata['SV' + str(i)].shift(1) - mydata['SV1']) / result['buyVolume10'].shift(1))[
                select]
            pass
        result['sellForce'] = 0
        for i in range(1, 11):
            select = (mydata['B1'] < mydata['B' + str(i)].shift(1)) & select0
            result.loc[select, 'sellForce'] = \
            (result['sellForce'] + mydata['BV' + str(i)].shift(1) / result['sellVolume10'].shift(1))[select]
            select = (mydata['B1'] == mydata['B' + str(i)].shift(1)) & (
                        mydata['BV' + str(i)].shift(1) > mydata['BV1']) & select0
            result.loc[select, 'sellForce'] = \
            (result['sellForce'] + (mydata['BV' + str(i)].shift(1) - mydata['BV1']) / result['sellVolume10'].shift(1))[
                select]
            pass
        return result[['buyForce', 'sellForce']]
        pass

    def __buySellVolumeVwapCheck(self, resultArr, myindex, n):
        length = resultArr.shape[0]
        result = np.zeros([length, 2])
        for k in range(length):
            buyVolume = 0
            sellVolume = 0
            buyAmount = 0
            sellAmount = 0
            for i in range(1, n + 1):
                buyVolume += resultArr[k, myindex['BV' + str(i)]]
                sellVolume += resultArr[k, myindex['SV' + str(i)]]
                buyAmount += resultArr[k, myindex['BV' + str(i)]] * resultArr[k, myindex['B' + str(i)]]
                sellAmount += resultArr[k, myindex['SV' + str(i)]] * resultArr[k, myindex['S' + str(i)]]
            result[k, 0] = buyAmount / buyVolume
            result[k, 1] = sellAmount / sellVolume
        # result=pd.DataFrame(result,columns=['buyVwap','sellVwap'])
        return result
        pass

    def __buySellVolumeVwap(self, mydata, n):
        result = mydata.copy()
        result['buyVolume'] = 0
        result['sellVolume'] = 0
        result['buyAmount'] = 0
        result['sellAmount'] = 0
        for i in range(1, n + 1):
            result['buyVolume'] = result['buyVolume'] + mydata['BV' + str(i)]
            result['sellVolume'] = result['sellVolume'] + mydata['SV' + str(i)]
            result['buyAmount'] = result['buyAmount'] + mydata['BV' + str(i)] * mydata['B' + str(i)]
            result['sellAmount'] = result['sellAmount'] + mydata['SV' + str(i)] * mydata['S' + str(i)]
        result['buyVwap'] = result['buyAmount'] / result['buyVolume']
        result['sellVwap'] = result['sellAmount'] / result['sellVolume']
        result[['buyVwap', 'sellVwap']] = result[['buyVwap', 'sellVwap']].replace(np.inf, np.nan)
        result[['buyVwap', 'sellVwap']] = result[['buyVwap', 'sellVwap']].replace(-np.inf, np.nan)
        result[['buyVwap', 'sellVwap']] = result[['buyVwap', 'sellVwap']].fillna(0)
        return result[['buyVwap', 'sellVwap']]

    # ----------------------------------------------------------------------
    def __buySellAmountForce(self, data):
        result = data.copy()
        select0 = (result['S1'] > result['B1']) & (result['B1'] > 0) & (result['S1'].shift(1) > result['B1'].shift(1)) & (result['B1'].shift(1) > 0)  # bid ask 价格不相同并且没有涨跌停
        result['buyForce'] = 0
        for i in range(1, 11):
            select = (result['S1'] > result['S' + str(i)].shift(1)) & select0
            result.loc[select, 'buyForce'] = (result['buyForce'] + result['SV' + str(i)].shift(1) * result['S' + str(i)].shift(1) / (1 + np.exp(-1000 * (result['S' + str(i)].shift(1) / result['midPrice'].shift(1) - 1))))[select]
            select = (result['S1'] == result['S' + str(i)].shift(1)) & (result['SV' + str(i)].shift(1) > result['SV1']) & select0
            result.loc[select, 'buyForce'] = (result['buyForce'] + (result['SV' + str(i)].shift(1) - result['SV1']) * result['S' + str(i)].shift(1) / (1 + np.exp(-1000 * (result['S' + str(i)].shift(1) / result['midPrice'].shift(1) - 1))))[select]
            pass
        result['sellForce'] = 0
        for i in range(1, 11):
            select = (result['B1'] < result['B' + str(i)].shift(1)) & select0
            result.loc[select, 'sellForce'] = (result['sellForce'] + result['BV' + str(i)].shift(1) * result['B' + str(i)].shift(1) / (1 + np.exp(1000 * (result['B' + str(i)].shift(1) / result['midPrice'].shift(1) - 1))))[select]
            select = (result['B1'] == result['B' + str(i)].shift(1)) & (result['BV' + str(i)].shift(1) > result['BV1']) & select0
            result.loc[select, 'sellForce'] = (result['sellForce'] + (result['BV' + str(i)].shift(1) - result['BV1']) * result[ 'B' + str(i)].shift(1) / (1 + np.exp(1000 * (result['B' + str(i)].shift(1) / result['midPrice'].shift(1) - 1))))[select]
            pass
        return result[['buyForce', 'sellForce']]
        pass

    def __getMidInToPrice(self, data, col, colup, coldown):
        result = data[[col, colup, coldown]].copy()
        result['ratio'] = (result[col] - (result[colup] + result[coldown]) / 2) / (result[colup] - result[coldown])
        select = (result[colup] == 0)
        result.loc[select, 'ratio'] = -1
        select = (result[coldown] == 0)
        result.loc[select, 'ratio'] = 1
        return result['ratio']
        pass

    # ----------------------------------------------------------------------
    def __volumeMagnification(self, data, fast, slow):
        result = data.copy()
        result['fast'] = super().EMA(result['volumeIncrease'], fast)
        result['slow'] = super().EMA(result['volumeIncrease'], slow)
        result['magnification'] = 0
        select = result['slow'] > 0
        result.loc[select, 'magnification'] = result['fast'] / result['slow']
        return result['magnification']
        pass

    # ----------------------------------------------------------------------
    def __computeVwapInfosCheck(self, resultArr, myindex, n):
        colname = 'vwap' + str(n) + 'ticks'
        colname2 = 'amount' + str(n) + 'ticks'
        colname3 = 'volume' + str(n) + 'ticks'
        length = resultArr.shape[0]
        result = np.zeros([length, 3])
        for k in range(length):
            amount = resultArr[k, myindex['amount']]
            volume = resultArr[k, myindex['volume']]
            midPrice = resultArr[k, myindex['midPrice']]
            lastIndex = max(k - n, 0)
            amountLast = resultArr[lastIndex, myindex['amount']]
            volumeLast = resultArr[lastIndex, myindex['volume']]
            if (volume > volumeLast):
                vwap = (amount - amountLast) / (volume - volumeLast)
            else:
                vwap = midPrice

            result[k, 0] = vwap
            result[k, 1] = amount - amountLast
            result[k, 2] = volume - volumeLast
        return result

    # ----------------------------------------------------------------------
    def __computeVwapInfos(self, data, n):
        result = data[['midPrice', 'amount', 'volume']].copy()
        colname = 'vwap' + str(n) + 'ticks'
        colname2 = 'amount' + str(n) + 'ticks'
        colname3 = 'volume' + str(n) + 'ticks'
        result[colname] = (result['amount'] - result['amount'].shift(n)) / (result['volume'] - result['volume'].shift(n))
        result[colname2] = result['amount'] - result['amount'].shift(n)
        result[colname3] = result['volume'] - result['volume'].shift(n)
        select = result.index[0:n]
        result.loc[select, colname] = (result['amount'] - result['amount'].iloc[0]) / (result['volume'] - result['volume'].iloc[0])[select]
        result.loc[select, colname2] = (result['amount'] - result['amount'].iloc[0])[select]
        result.loc[select, colname3] = (result['volume'] - result['volume'].iloc[0])[select]
        result[colname] = result[colname].replace(np.inf, np.nan)
        result[colname] = result[colname].replace(-np.inf, np.nan)
        select = result[colname].isna() == True
        result.loc[select, colname] = result['midPrice'][select]

        # data[colname]=result[colname]
        return result[[colname, colname2, colname3]]
        pass

    # ----------------------------------------------------------------------
    def computerFactor(self, code, date, mydata):
        result = pd.DataFrame()
        if mydata.shape[0] != 0:
            # index对齐即可
            result = mydata.copy()
            # ---------------------------------------------------------------
            # 将dataframe转化为array计算
            myindex = {}
            columnsNames = list(result.columns)
            for item in result.columns:
                myindex.update({item: columnsNames.index(item)})
            resultArr = result.values
            length = resultArr.shape[0]

            result['buySellSpread'] = 0
            select = (mydata['S1'] != 0) & (mydata['B1'] != 0)
            result.loc[select, 'buySellSpread'] = ((mydata['S1'] - mydata['B1']) / mydata['midPrice'])[select]
            result['logbuySellSpread'] = np.log(result['buySellSpread'] + 0.00001)

            # ------------------------------------------------------------------
            # 计算buy sell vwap 相关的因子
            result[['buyVwap1', 'sellVwap1']] = self.__buySellVolumeVwap(mydata, 1)
            result[['buyVwap2', 'sellVwap2']] = self.__buySellVolumeVwap(mydata, 2)
            result[['buyVwap5', 'sellVwap5']] = self.__buySellVolumeVwap(mydata, 5)
            result[['buyVwap10', 'sellVwap10']] = self.__buySellVolumeVwap(mydata, 10)
            # arr=self.__buySellVolumeVwapCheck(resultArr,myindex,10)
            # result['buyVwap10Check']=arr[:,0]
            # result['sellVwap10Check']=arr[:,1]
            result['midInBuySellVwap1'] = self.__getMidInToPrice(result, 'midPrice', 'sellVwap1', 'buyVwap1')
            result['midInBuySellVwap2'] = self.__getMidInToPrice(result, 'midPrice', 'sellVwap2', 'buyVwap2')
            result['midInBuySellVwap5'] = self.__getMidInToPrice(result, 'midPrice', 'sellVwap5', 'buyVwap5')
            result['midInBuySellVwap10'] = self.__getMidInToPrice(result, 'midPrice', 'sellVwap10', 'buyVwap10')

            # result['buySellVwap1Spread']=0
            # select=(result['buyVwap1']!=0) & (result['sellVwap1']!=0)
            # result.loc[select,'buySellVwap1Spread']=((result['sellVwap1']-result['buyVwap1'])/result['midPrice'])[select]
            # result['logbuySellVwap1Spread']=np.log(result['buySellVwap1Spread']+0.00001)


            # ------------------------------------------------------------------
            # 买卖盘口静态信息,因子值为正整数
            result['buyVolume2'] = mydata['BV1'] + mydata['BV2']
            result['sellVolume2'] = mydata['SV1'] + mydata['SV2']
            result['buyVolume5'] = (mydata['BV1'] + mydata['BV2'] + mydata['BV3'] + mydata['BV4'] + mydata['BV5'])
            result['sellVolume5'] = (mydata['SV1'] + mydata['SV2'] + mydata['SV3'] + mydata['SV4'] + mydata['SV5'])
            result['buyVolume10'] = (mydata['BV1'] + mydata['BV2'] + mydata['BV3'] + mydata['BV4'] + mydata['BV5'] + mydata['BV6'] + mydata['BV7'] + mydata['BV8'] + mydata['BV9'] + mydata['BV10'])
            result['sellVolume10'] = ( mydata['SV1'] + mydata['SV2'] + mydata['SV3'] + mydata['SV4'] + mydata['SV5'] + mydata['SV6'] + mydata['SV7'] + mydata['SV8'] + mydata['SV9'] + mydata['SV10'])
            result['totalVolume10'] = result['buyVolume10'] + result['sellVolume10']
            # ------------------------------------------------------------------
            # 挂单量信息
            select = (result['sellVolume10'] + result['buyVolume10']) == 0
            result['buySellVolumeRatio2'] = (result['buyVolume2'] / (result['sellVolume2'] + result['buyVolume2']))
            result['buySellVolumeRatio5'] = (result['buyVolume5'] / (result['sellVolume5'] + result['buyVolume5']))
            result['buySellVolumeRatio10'] = (result['buyVolume10'] / (result['sellVolume10'] + result['buyVolume10']))
            result.loc[select, 'buySellVolumeRatio2'] = 0
            result.loc[select, 'buySellVolumeRatio5'] = 0
            result.loc[select, 'buySellVolumeRatio10'] = 0
            # ------------------------------------------------------------------
            # 加权之后的多空力量对比
            # 根据价格和量计算的多空力量对比因子值在[0,1]之间
            self.__buySellWeightedVolumeRatio(result, 2)
            self.__buySellWeightedVolumeRatio(result, 5)
            self.__buySellWeightedVolumeRatio(result, 10)
            # -----------------------------------------------------------------
            result[['buyAverageVolumeWeighted1_10_80', 'sellAverageVolumeWeighted1_10_80']] = self.__averageVolumeWeighted(result, 1, 10, 0.8)
            result[['buyAverageVolumeWeighted1_10_80', 'sellAverageVolumeWeighted1_10_80']] = np.log( result[['buyAverageVolumeWeighted1_10_80', 'sellAverageVolumeWeighted1_10_80']] + 1)

            result[['buyAverageVolume1_10', 'sellAverageVolume1_10']] = self.__averageVolumeWeighted(result, 1, 10, 1)
            result[['buyAverageVolume1_10', 'sellAverageVolume1_10']] = np.log(result[['buyAverageVolume1_10', 'sellAverageVolume1_10']] + 1)

            result[ ['buyAverageAmountWeighted1_10_80', 'sellAverageAmountWeighted1_10_80']] = self.__averageAmountWeighted(result, 1, 10, 0.8)
            result[['buyAverageAmountWeighted1_10_80', 'sellAverageAmountWeighted1_10_80']] = np.log(result[['buyAverageAmountWeighted1_10_80', 'sellAverageAmountWeighted1_10_80']] + 1)

            result['buySellVolumeWeightedPressure1_10_80'] = self.__buySellVolumeWeightedPressure(result, 1, 10, 0.8)
            result['EMABuySellVolumeWeightedPressure1_10_80'] = super().EMA(result['buySellVolumeWeightedPressure1_10_80'], 5)

            result['buySellAmountWeightedPressure1_10_80'] = self.__buySellAmountWeightedPressure(result, 1, 10, 0.8)
            result['EMABuySellAmountWeightedPressure1_10_80'] = super().EMA(
                result['buySellAmountWeightedPressure1_10_80'], 5)

            result['buySellPress1_10'] = self.__buySellPressure(result, 1, 10)

            result['EMABuySellPress1_10'] = super().EMA(result['buySellPress1_10'], 10)

            # ------------------------------------------------------------------
            # 主动买和主动卖，因子值大小在[0,+∞)
            result[['buyForce', 'sellForce']] = self.__buySellAmountForce(result)

            result['EMABuyForce15'] = super().EMA(result['buyForce'], 15)
            result['EMASellForce15'] = super().EMA(result['sellForce'], 15)

            result['buyForce'] = np.log(result['buyForce'] + 1)
            result['sellForce'] = np.log(result['sellForce'] + 1)

            result['EMABuyForce15'] = np.log(result['EMABuyForce15'] + 1)
            result['EMASellForce15'] = np.log(result['EMASellForce15'] + 1)

            result['buySellForceChange'] = result['EMABuyForce15'] - result['EMASellForce15']
            # ------------------------------------------------------------------
            # 考察多个tick的主动买和主动卖，vwap价格比mid高的认为是主动买，vwap价格比mid低的认为是主动卖
            result[['vwap1Tick', 'amount1Tick', 'volume1tick']] = self.__computeVwapInfos(result, 1)

            # arr=self.__computeVwapInfosCheck(resultArr,myindex,1)
            # result['vwap1TickCheck']=arr[:,0]

            result['activeBuying'] = 0
            result['activeBuyingIncrease'] = 0
            select = result['vwap1Tick'] > result['midPrice']
            result.loc[select, 'activeBuying'] = 1
            result.loc[select, 'activeBuyingIncrease'] = (result['vwap1Tick'] - result['midPrice']) / \
                                                         result['midPrice'][select]
            result['activeSelling'] = 0
            result['activeSellingDecrease'] = 0
            select = result['vwap1Tick'] < result['midPrice']
            result.loc[select, 'activeSelling'] = 1
            result.loc[select, 'activeSellingDecrease'] = (result['vwap1Tick'] - result['midPrice']) / \
                                                          result['midPrice'][select]

            result['activeBuyingIncreaseMean2m'] = result['activeBuyingIncrease'].rolling(40, min_periods=1).apply(
                lambda x: np.mean(x[x > 0]), raw=True)
            result['activeSellingDecreaseMean2m'] = result['activeSellingDecrease'].rolling(40, min_periods=1).apply(
                lambda x: np.mean(x[x < 0]), raw=True)
            result['activeBuyingIncreaseMean5m'] = result['activeBuyingIncrease'].rolling(100, min_periods=1).apply(
                lambda x: np.mean(x[x > 0]), raw=True)
            result['activeSellingDecreaseMean5m'] = result['activeSellingDecrease'].rolling(100, min_periods=1).apply(
                lambda x: np.mean(x[x < 0]), raw=True)
            result['activeBuyingIncreaseMean10m'] = result['activeBuyingIncrease'].rolling(200, min_periods=1).apply(
                lambda x: np.mean(x[x > 0]), raw=True)
            result['activeSellingDecreaseMean10m'] = result['activeSellingDecrease'].rolling(200, min_periods=1).apply(
                lambda x: np.mean(x[x < 0]), raw=True)
            result['activeBuyingIncreaseMean30m'] = result['activeBuyingIncrease'].rolling(600, min_periods=1).apply(
                lambda x: np.mean(x[x > 0]), raw=True)
            result['activeSellingDecreaseMean30m'] = result['activeSellingDecrease'].rolling(600, min_periods=1).apply(
                lambda x: np.mean(x[x < 0]), raw=True)
            # 将NAN强制赋值为0
            result['activeBuyingIncreaseMean2m'] = result['activeBuyingIncreaseMean2m'].fillna(0)
            result['activeSellingDecreaseMean2m'] = result['activeSellingDecreaseMean2m'].fillna(0)
            result['activeBuyingIncreaseMean5m'] = result['activeBuyingIncreaseMean5m'].fillna(0)
            result['activeSellingDecreaseMean5m'] = result['activeSellingDecreaseMean5m'].fillna(0)
            result['activeBuyingIncreaseMean10m'] = result['activeBuyingIncreaseMean10m'].fillna(0)
            result['activeSellingDecreaseMean10m'] = result['activeSellingDecreaseMean10m'].fillna(0)
            result['activeBuyingIncreaseMean30m'] = result['activeBuyingIncreaseMean30m'].fillna(0)
            result['activeSellingDecreaseMean30m'] = result['activeSellingDecreaseMean30m'].fillna(0)

            result['activeBuyingAmount'] = result['amount1Tick'] * result['activeBuying']
            result['activeSellingAmount'] = result['amount1Tick'] * result['activeSelling']
            result['activeBuyingAmountTotal2m'] = result['activeBuyingAmount'].rolling(40, min_periods=1).sum()
            result['activeSellingAmountTotal2m'] = result['activeSellingAmount'].rolling(40, min_periods=1).sum()
            result['activeBuyingAmountTotal5m'] = result['activeBuyingAmount'].rolling(100, min_periods=1).sum()
            result['activeSellingAmountTotal5m'] = result['activeSellingAmount'].rolling(100, min_periods=1).sum()
            result['activeBuyingAmountTotal10m'] = result['activeBuyingAmount'].rolling(200, min_periods=1).sum()
            result['activeSellingAmountTotal10m'] = result['activeSellingAmount'].rolling(200, min_periods=1).sum()
            result['activeBuyingAmountTotal30m'] = result['activeBuyingAmount'].rolling(600, min_periods=1).sum()
            result['activeSellingAmountTotal30m'] = result['activeSellingAmount'].rolling(600, min_periods=1).sum()
            result['activeBuyingSellingAmountRatio2m'] = result['activeBuyingAmountTotal2m'] / (
                        result['activeBuyingAmountTotal2m'] + result['activeSellingAmountTotal2m'] + 0.01)
            result['activeBuyingSellingAmountRatio5m'] = result['activeBuyingAmountTotal5m'] / (
                        result['activeBuyingAmountTotal5m'] + result['activeSellingAmountTotal5m'] + 0.01)
            result['activeBuyingSellingAmountRatio10m'] = result['activeBuyingAmountTotal10m'] / (
                        result['activeBuyingAmountTotal10m'] + result['activeSellingAmountTotal10m'] + 0.01)
            result['activeBuyingSellingAmountRatio30m'] = result['activeBuyingAmountTotal30m'] / (
                        result['activeBuyingAmountTotal30m'] + result['activeSellingAmountTotal30m'] + 0.01)
            result['volumeIncreaseMA3']=super().MA(result['volumeIncrease'],3)
            result['volumeIncreaseMA20']=super().MA(result['volumeIncrease'],20)
            result['volumeIncreaseMA40']=super().MA(result['volumeIncrease'],40)
            result['volumeIncreaseMA100']=super().MA(result['volumeIncrease'],100)
            result['volumeIncreaseMA200']=super().MA(result['volumeIncrease'],200)
            result['volumeIncreaseMA3']=super().logWithLowerBound(result['volumeIncreaseMA3'],0)
            result['volumeIncreaseMA20']=super().logWithLowerBound(result['volumeIncreaseMA20'],0)
            result['volumeIncreaseMA40']=super().logWithLowerBound(result['volumeIncreaseMA40'],0)
            result['volumeIncreaseMA100']=super().logWithLowerBound(result['volumeIncreaseMA100'],0)
            result['volumeIncreaseMA200']=super().logWithLowerBound(result['volumeIncreaseMA200'],0)

            result = result[result['tick'] < '144700000']
            mycolumns = list(set(result.columns).difference(set(mydata.columns)))
            mycolumns.sort()
            result = result[mycolumns]
            super().checkDataNan(code, date, self.factor, result)
            pass
        else:
            logger.error(f'There no data of {code} in {date} to computer factor!')
        return result
#